﻿using Microsoft.AspNetCore.Mvc;
using MS.Core.BaseProvider;
using MS.Core.Model;
using ReportDesignerServer.DataModel;
using ReportDesignerServer.DataModels;
using ReportDesignerServer.Dto;
using ReportDesignerServer.IRepository;
using ReportDesignerServer.Repository;
using SqlSugar;

namespace ReportDesignerServer.Services
{
    /// <summary>
    /// 患者在科记录
    /// </summary>
    public class PatientInHospitalService : ServiceBase<PatientInHospital, IPatientInHospitalRepository>
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="patientInHospitalRepository"></param>
        public PatientInHospitalService(IPatientInHospitalRepository patientInHospitalRepository)
        {
            this.Repository = patientInHospitalRepository;
        }


        public Rt QueryPatientInHospital()
        {
            Expressionable<PatientInHospital> exp = Expressionable.Create<PatientInHospital>();
            exp.And(it => it.ISOUT == 0);
            var list = Repository.GetListByWhere(exp);
            
            return Rt.SuccessObj(list);
        }



        public Rt GetPatientInHospitalById(string id)
        {
            long lid = 0;
            if (long.TryParse(id, out lid))
            {
                Expressionable<PatientInHospital> exp = Expressionable.Create<PatientInHospital>();
                exp.And(it => it.ID == lid);
                var model = Repository.GetListByWhere(exp).FirstOrDefault();
                return Rt.SuccessObj(model);
            }
            else
            {
                return Rt.Error();
            }
        }



        public Rt SavePatientInHospital([FromBody] PatientInHospital model)
        {
            long res = 0;
            if (model != null)
            {
                if (model.ID == 0)
                {
                    Expressionable<PatientInHospital> exp = Expressionable.Create<PatientInHospital>();
                    exp.And(it => it.PATIENTID == model.PATIENTID);
                    exp.And(it => it.ISOUT == 0);
                    var patList = Repository.GetListByWhere(exp);
                    if (patList?.Count == 0)
                    {
                        //所有添加的数据，都是未出科
                        model.ISOUT = 0;
                        res = Repository.ExecuteReturnSnowflakeId(model);
                    }
                    else
                    {

                        return Rt.Fail("该患者ID已存在未出科数据！");
                    }
                }
                else
                {
                    res = Repository.Update(model);
                }
            }
            if (res > 0)
            {
                return Rt.Success();
            }
            else
            {
                return Rt.Error();
            }
        }
    }
}
